import React from 'react';
import { withRouter, router } from 'umi';
import { Toast } from 'antd-mobile';
import { createForm } from 'rc-form';
import { Button, Password, Header, Tips, Email } from './components';
import { useOldLogin } from '../hooks';
import { getLoginInfo, updatePassword, getCheckAccount } from '../service';

const OldLoginMobile = ({ form, location }) => {
    const { query, pathname } = location;
    const { getFieldProps } = form;
    const [submitLoading, setSubmitLoading] = React.useState(false);

    const [modifyPwdSafetyCode, setModifyPwdSafetyCode] = React.useState(false);
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { loading: loginLoading, handleLogin } = useOldLogin(location);

    // const list = [
    //     {
    //         key: '用户名称',
    //         value: '--'
    //     },
    //     {
    //         key: '手机号',
    //         value: '--'
    //     },
    //     {
    //         key: '账号',
    //         value: '--'
    //     }
    // ];
    const getAccount = async talentEmail => {
        try {
            let otherPara = {};
            if (pathname.includes('interview')) {
                otherPara = { interviewNoticeId: query?.id };
            } else if (pathname.includes('candidate')) {
                otherPara = { backgroundId: query?.signCandidateId };
            } else if (pathname.includes('hireConfirm')) {
                otherPara = { employId: query?.employId };
            } else {
                otherPara = query;
            }

            const result = await getCheckAccount(talentEmail, otherPara);
            const { code, data, msg } = result;
            if (code === 10000) {
                const { candidateLinkId, hasCandidateAccount } = data;
                if (!hasCandidateAccount) {
                    if (modifyPwdSafetyCode) {
                        return candidateLinkId;
                    }
                    setModifyPwdSafetyCode(true);
                    form.resetFields(['password', 'password2']);

                    Toast.info('候选人尚未有账号，请先设置账号');
                    setSubmitLoading(false);
                    return null;
                }
                return candidateLinkId;
            }
            Toast.info(msg);
            setSubmitLoading(false);
            return null;
        } catch (error) {
            setSubmitLoading(false);
            return null;
        }
    };
    const handleSubmit = () => {
        form.validateFields(async (err, values) => {
            // console.log('handleSubmit -> values', values);
            if (!err) {
                setSubmitLoading(true);
                // 设置账号
                if (modifyPwdSafetyCode) {
                    try {
                        // 创建账号
                        const id = await getAccount(values.talentEmail);
                        console.log('candidateLinkId000---', id);
                        if (id) {
                            const loginInfo = await getLoginInfo(id);

                            if (loginInfo?.code === 10000) {
                                const data = loginInfo?.data;
                                if (data?.modifyPwdSafetyCode) {
                                    const updateResult = await updatePassword({
                                        key: data?.modifyPwdSafetyCode,
                                        password: values.password
                                    });
                                    if (updateResult?.code === 10000) {
                                        await handleLogin({
                                            talentEmail: values?.talentEmail,
                                            password: values.password,
                                            id
                                        });
                                        setSubmitLoading(false);
                                    } else {
                                        setSubmitLoading(false);
                                        Toast.info(updateResult?.msg);
                                    }
                                }
                            } else {
                                setSubmitLoading(false);
                                Toast.info(loginInfo?.msg);
                            }
                        }
                    } catch (error) {
                        setSubmitLoading(false);
                    }
                } else {
                    try {
                        // 获取id
                        const id = await getAccount(values.talentEmail);
                        if (id) {
                            await handleLogin({
                                talentEmail: values?.talentEmail,
                                password: values.password,
                                id
                            });
                            setSubmitLoading(false);
                        }
                    } catch (error) {
                        setSubmitLoading(false);
                    }
                }
            }
        });
    };

    // const detailStyle = {
    //     style: { marginBottom: 8 },
    //     keyStyle: {
    //         width: '5.5em',
    //         textAlign: 'right',
    //         fontSize: 14,
    //         color: '#858B9B',
    //         fontWeight: 500
    //     },
    //     valueStyle: {
    //         fontSize: 14,
    //         color: '#2A2F3C'
    //     }
    // };
    const forget = async () => {
        try {
            setSubmitLoading(true);
            const email = form.getFieldValue('talentEmail') || '';
            const id = await getAccount(email);
            setSubmitLoading(false);
            if (id) {
                history.push({
                    pathname: '/external/interview/resetPassword',
                    query: {
                        email: form.getFieldValue('talentEmail'),
                        id
                    }
                });
            }
        } catch (error) {
            setSubmitLoading(false);
        }
    };
    const pageStyle = modifyPwdSafetyCode
        ? {}
        : {
              minHeight: '100%',
              background: '#fff'
          };

    return (
        <div style={pageStyle}>
            <div style={{ background: '#fff', marginBottom: modifyPwdSafetyCode ? 8 : 0 }}>
                <Header />
                {modifyPwdSafetyCode ? (
                    <Tips
                        title="已为您开通候选人帐号，请设置密码并登录"
                        content="该账号也将在后续应聘过程中使用，请妥善保管"
                    />
                ) : (
                    <div
                        style={{
                            padding: '0 24px',
                            color: '#2A2F3C',
                            marginTop: 24,
                            fontSize: 20,
                            fontWeight: 600,
                            lineHeight: '32px'
                        }}
                    >
                        你好，欢迎应聘微微科技有限公司
                    </div>
                )}
            </div>
            <div style={{ background: '#fff', padding: modifyPwdSafetyCode ? 16 : 24 }}>
                {/* <div
                    style={{
                        background: '#fafafa',
                        padding: '16px 16px 8px 12px',
                        borderRadius: 4,
                        border: '1px solid #F2F3F4',
                        marginBottom: 20
                    }}
                >
                    <InterviewDetail dataSource={list} {...detailStyle} />
                </div> */}

                <Email
                    label="账号"
                    {...getFieldProps('talentEmail', {
                        rules: [
                            {
                                required: true,
                                whiteSpace: true,
                                message: '请输入账号'
                            },
                            {
                                validator(rule, value, callback) {
                                    const regex = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
                                    if (value) {
                                        const tempValue = value.trim();
                                        if (regex.test(tempValue)) {
                                            callback();
                                        } else {
                                            callback('请输入正确的个人邮箱');
                                        }
                                    }
                                    callback();
                                }
                            }
                        ]
                    })}
                    error={form.getFieldError('talentEmail')}
                    errorText={form.getFieldError('talentEmail')}
                    placeholder="请输入账号"
                    clear
                />
                <Password
                    label={modifyPwdSafetyCode ? '设置密码' : '密码'}
                    {...getFieldProps('password', {
                        rules: [
                            {
                                required: true,
                                whiteSpace: true,
                                message: '请输入密码'
                            },
                            {
                                validator(rule, value, callback) {
                                    const regex = /^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])).*$/;
                                    if (value) {
                                        const tempValue = value.trim();
                                        if (!regex.test(value)) {
                                            callback('密码需包含大小写英文及数字');
                                        } else if (tempValue.length < 8 || tempValue.length > 20) {
                                            callback('密码8-20位');
                                        } else {
                                            callback();
                                        }
                                    }
                                    callback();
                                }
                            }
                        ]
                    })}
                    error={form.getFieldError('password')}
                    errorText={form.getFieldError('password')}
                    placeholder="请输入密码"
                    maxLength={20}
                    clear
                />
                {modifyPwdSafetyCode && (
                    <Password
                        label="确认密码"
                        {...getFieldProps('password2', {
                            rules: [
                                {
                                    required: true,
                                    whiteSpace: true,
                                    message: '请输入确认密码'
                                },
                                {
                                    validator(rule, value, callback) {
                                        if (value) {
                                            const tempValue = value.trim();
                                            const password = form.getFieldValue('password').trim();
                                            if (tempValue === password) {
                                                callback();
                                            } else {
                                                callback('两次输入的密码不相同');
                                            }
                                        }
                                        callback();
                                    }
                                }
                            ]
                        })}
                        error={form.getFieldError('password2')}
                        errorText={form.getFieldError('password2')}
                        placeholder="请输入确认密码"
                        maxLength={20}
                        clear
                    />
                )}
                <Button
                    type="primary"
                    loading={submitLoading || loginLoading}
                    style={{ marginTop: 12 }}
                    onClick={handleSubmit}
                >
                    {modifyPwdSafetyCode ? '设置并登录' : '登录'}
                </Button>
                {!modifyPwdSafetyCode && (
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <div style={{ padding: '12px 0' }}>
                            <span style={{ fontSize: 14, lineHeight: '20px' }}>没有账号？</span>
                            <span
                                onClick={() => {
                                    setModifyPwdSafetyCode(true);
                                    form.resetFields(['password', 'password2']);
                                }}
                                style={{ color: '#2D87FF', fontSize: 14, lineHeight: '20px' }}
                            >
                                立即创建
                            </span>
                        </div>
                        <div style={{ padding: '12px 0' }} onClick={async () => forget()}>
                            <div style={{ color: '#2D87FF', fontSize: 14, lineHeight: '20px' }}>忘记密码</div>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

export default withRouter(createForm()(OldLoginMobile));
